<template>
  <el-dialog :title="showMyTitle" :visible="showDialog" @close="close">

    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="2-10字符" style="width:80%" size="mini" />
      </el-form-item>

      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" placeholder="2-10字符" style="width:80%" size="mini" />
      </el-form-item>

      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width:80%" size="mini">
          <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" placeholder="5-100字符" type="textarea" :rows="4" style="width:80%" size="mini" />
      </el-form-item>

      <el-form-item>
        <!-- 想要弹性布局，可以用el-row和el-col标签进行布局 -->
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
            <el-button size="mini" @click="close()">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getDepartment, getManagerList, addDepartment, addDepartmentDetail, updateDepartment } from '@/api/department'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    currentNodeId: { // 当前部门的id
      type: Number,
      default: null
    }
  },
  data() {
    return {
      showTitle: '',
      managerList: [],
      formData: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        managerId: '', // 部门负责人id
        name: '', // 部门名称
        pid: '' // 父级部门的id
      },
      rules: {
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码长度为2-10个字符', trigger: 'blur' },
          // 自定义校验，校验部门编码是否重复。vaulue就是当前的部门编码
          { trigger: 'blur', validator: async(rule, value, callback) => {
            let res = await getDepartment()
            if (this.formData.id) {
              // 说明是编辑状态，需要排除自己
              res = res.filter(item => item.id !== this.formData.id)
            }
            if (res.some(item => item.code === value)) {
              callback(new Error('部门编码重复'))
            } else {
              callback()
            }
          } }
        ],
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门介绍长度为5-100个字符', trigger: 'blur' }
        ],
        managerId: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称长度为2-10个字符', trigger: 'blur' },
          // 编辑部门时，要去掉自身
          { trigger: 'blur', validator: async(rule, value, callback) => {
            let res = await getDepartment()
            if (this.formData.id) {
              // 说明是编辑状态，需要排除自己
              res = res.filter(item => item.id !== this.formData.id)
            }
            if (res.some(item => item.name === value)) {
              callback(new Error('部门名称重复'))
            } else {
              callback()
            }
          } }
        ]
      }
    }
  },
  computed: {
    showMyTitle() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getManagerList()
  },
  methods: {
    btnOk() {
      //  先校验表单
      this.$refs.addDept.validate(async isOk => {
        if (isOk) {
          let msg = '新增'
          if (this.formData.id) {
            // 编辑
            msg = '编辑'
            await updateDepartment(this.formData)
          } else {
            // ...展开运算符，展开对象里的所有属性，后面再添加相同的属性会覆盖前面的
            // 我们要把当前的部门的pid设为父级部门的id（currentNodeId时父级的id）
            await addDepartment({ ...this.formData, pid: this.currentNodeId })
          }
          // 通知父组件更新
          this.$emit('updateDepartment')
          // 不同场景，提示不同
          this.$message.success(`${msg}部门成功`)
          this.close()
        }
      })
    },
    close() {
      // resetFields只能重置再模板中绑定的数据，需要重置表单的属性
      this.formData = {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        managerId: '', // 部门负责人id
        name: '', // 部门名称
        pid: '' // 父级部门的id
      }
      this.$refs.addDept.resetFields()
      this.$emit('update:showDialog', false)
    },
    async getManagerList() {
      this.managerList = await getManagerList()
    },
    // 获取组织的详情
    async getDepartmentDetail() {
      this.formData = await addDepartmentDetail(this.currentNodeId)
    }
  }
}
</script>

